var status = 0;   // 0: 编辑 1： 增加

var thisPage = {
    first: 0,
    // 得到系统资源数据
    GetEntityData: function () {
        let item = {};
        item['resourceId'] = ($("#ResourceId").val().length > 0) ? $("#ResourceId").val() : 0;
        item['parentId'] = ($("#ParentId").val().length > 0) ? $("#ParentId").val() : 0;
        item['orderNo'] = $.trim($("#OrderNo").val());
        item['resourceName'] = $.trim($("#ResourceName").val());
        item['linkUrl'] = $.trim($("#LinkUrl").val());
        item['description'] = formatNullInputValue($.trim($("#Description").val()));
        item['actionList'] = thisPage.GetSelectedAction();

        return JSON.stringify(item);
    },
    // 取得被选择的操作数据
    GetSelectedAction: function () {
        let actionList = [];
        $("input[type='checkbox'][name='action']:checked").each(function () {
            let _actionId = $(this).attr("data_value");
            let item = {};
            item['actionId'] = _actionId;
            actionList.push(item);
        });
        return actionList;
    },
    // 初始化页面,得到树形节点数据
    OnPageLoad: function () {
        // 设置系统操作选择区域
        $.ajax({
            type: "POST",
            async: false,
            url: parent.basePath + '/admin/resource/fetchAllAction.html',
            timeout: 30 * 1000,
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            let html = "";
            for (var i = 0; i < data.length; i++) {
                html = html +
                        '<span style="margin-right:8px;float:left;">' +
                        '    <input style="vertical-align:-2px;" type="checkbox" name="action" id="c-' + data[i].actionId + '" data_value="' + data[i].actionId + '" onchange="checkField($(this))">' +
                        '    <label class="normal" for="c-' + data[i].actionId + '">' + data[i].actionName + '</label>' +
                        '</span>';
                if ((i > 0) && ((i % 7) === 0)) {
                    html = html + '<br style="clear:both" />';
                }
            }

            $("#ActionWrapper").html(html);
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function ( ) {
        });

        // 初始化树形控件
        $('#treeContent').jstree({
            "core": {
                "animation": 200,
                "multiple": false,
                "check_callback": true,
                "themes": {
                    "responsive": true,
                    "dots": false,
                    "icons": true
                },
                "data": {
                    'dataType': 'JSON',
                    'contentType': "application/json; charset=utf-8",
                    'type': "GET",
                    'url': parent.basePath + '/admin/resource/tree.html',
                    'data': (node) => {
                        let _nodeId = node.id === '#' ? -1 : (node.id === 'j1_1' ? 0 : node.id);
                        return {'parentKey': _nodeId};
                    },
                    'complete': () => {
                        $("#loading").hide();
                    }
                }
            },
            "types": {
                "#": {"max_depth": -1, "max_children": -1, "valid_children": ["root"]},
                "root": {"max_depth": -1, "max_children": -1, "icon": parent.basePath + "/images/tree/root.png", "valid_children": -1},
                "default": {"max_depth": -1, "max_children": -1, "valid_children": -1},
                "leaf": {"max_depth": -1, "max_children": -1, "icon": parent.basePath + "/images/tree/folder_close.png", "valid_children": -1}
            },
            "plugins": ["dnd", "contextmenu", "types", "wholerow"],
            "dnd": {
                "copy": false
            },
            "contextmenu": {
                "items": {
                    "create": {
                        "label": "新建功能",
                        "icon": parent.basePath + "/images/tree/add.png",
                        "action": function (data) {
                            let inst = jQuery.jstree.reference(data.reference),
                                    obj = inst.get_node(data.reference);
                            //dialog.show({"title": "新建“" + obj.text + "”的子菜单", url: "/accountmanage/createMenu?id=" + obj.id, height: 280, width: 400});
                            thisPage.DoInsert();
                        }
                    },
                    "edit": {
                        "label": "编辑功能",
                        "icon": parent.basePath + "/images/tree/edit.png",
                        "action": function (data) {
                            let inst = jQuery.jstree.reference(data.reference),
                                    obj = inst.get_node(data.reference);
                            //dialog.show({"title": "编辑“" + obj.text + "”菜单", url: "/accountmanage/editMenu?id=" + obj.id, height: 280, width: 400});
                        },
                        "separator_after": true
                    },
                    "remove": {
                        "label": "删除功能",
                        "icon": parent.basePath + "/images/tree/delete.png",
                        "action": function (data) {
                            let inst = jQuery.jstree.reference(data.reference),
                                    obj = inst.get_node(data.reference);
                            thisPage.DoDelete();
                        }
                    }
                }
            }
        });
        // 树形节点选择
        $('#treeContent').on('select_node.jstree', function (event, data) {
            // 清除错误状态
            thisPage.ClearForm();

            let _selectedNodeId = data.node.id;
            let _select_node = $("#" + _selectedNodeId);

            if (_selectedNodeId !== "j1_1") {
                $("#OperateMode").html("<i class='fa-all fa-fw fa-pencil-square-o'></i>【操作状态】：编辑系统资源");
                status = 0; // 设置编辑状态
                let ref = $.jstree.reference('treeContent');
                let _parentId = ref.get_parent(_select_node);
                let _parent_node = $("#" + _parentId);
                $('#ParentResourceName').val(_parent_node.attr("fullname"));

                // 重新设置选择的结点ID
                _selectedNodeId = _selectedNodeId === "j1_1" ? 0 : _selectedNodeId;
                //$('#ParentId').val(_selectedNodeId);
                $('#id').val(_selectedNodeId);
                // 如果不是根节点，则取得相应的系统资源
                thisPage.FetchByKey(_selectedNodeId);
            } else {
                // 如果是根节点，清空右边表单内容，准备下一个记录
                $("#OperateMode").html("");
                $('#ParentResourceName').text("");
                status = -1; // 设置为无效状态
            }
        });
        // 节点展开后，重新设置图标
        $('#treeContent').on('open_node.jstree', function (event, data) {
            let ref = $.jstree.reference('treeContent');
            let _nodeIdOfSelected = data.node.id;
            let _nodeOfSelected = $("#" + _nodeIdOfSelected);
            if (_nodeIdOfSelected !== "j1_1")
                ref.set_icon(_nodeOfSelected, parent.basePath + "/images/tree/folder_open.png");
        });
        // 节点收回后，重新设置图标
        $('#treeContent').on('close_node.jstree', function (event, data) {
            let ref = $.jstree.reference('treeContent');
            let _nodeIdOfSelected = data.node.id;
            let _nodeOfSelected = $("#" + _nodeIdOfSelected);
            if (_nodeIdOfSelected !== "j1_1")
                ref.set_icon(_nodeOfSelected, parent.basePath + "/images/tree/folder_close.png");
        });
        // 删除节点后，设置父节点图标
        $('#treeContent').on('delete_node.jstree', function (event, data) {
            let ref = $.jstree.reference('treeContent');
            let _nodeIdOfSelectedParent = data.parent;
            let _nodeOfSelectedParent = $("#" + _nodeIdOfSelectedParent);
            if (_nodeIdOfSelectedParent !== "j1_1") {
                if (ref.is_leaf(_nodeOfSelectedParent) === true) {
                    ref.set_icon(_nodeOfSelectedParent, parent.basePath + "/images/tree/folder_close.png");
                }
            }
        });
        // 树形结点打开后
        $('#treeContent').on('after_open.jstree', function (event, data) {
            let ref = $.jstree.reference('treeContent');
            // 选择该结点
            let _newNode = $("#" + $("#ResourceId").val());
            if (_newNode.length > 0) {
                ref.select_node(_newNode);
            }
        });
        // 所有节点完成装载，只运行一次
        $('#treeContent').on('ready.jstree', () => {
            let ref = $.jstree.reference('treeContent');
            let _obj = $("#j1_1");
            ref.open_node(_obj);     // 打开当前第一层节点
            ref.select_node(_obj);
        });
        // 拖动节点结束后的事件
        $(document).on('dnd_stop.vakata', function (event, data) {
            if (data.element.parentNode.parentNode.parentNode.id === data.event.target.parentNode.id) {
                return false;
            }
            let parentNode = (data.event.target.parentNode.id === "j1_1") ? 0 : (data.event.target.parentNode.id);
            let params = {};
            params['ResourceId'] = parseInt(data.element.parentNode.id);   // 选择的节点
            params['ParentId'] = parseInt(parentNode);  // 目标节点

            $.ajax({
                type: "POST",
                url: parent.basePath + '/admin/resource/changeParentCatalogue.html',
                timeout: 30 * 1000,
                data: JSON.stringify(params),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: function () {
                }
            }).done(function (data) {
                if (parseInt(data) > 0) {
                    ShowSuccessMessagePanel("所属目录改变成功。");
                }
            }).fail(function (data) {
                parent.ajaxError(data, 1);
            }).always(function () {
            });
        });
    },
    // 创建新结点
    NewNode: function () {
        let node = {};
        let li_attr = {};
        node['id'] = $("#ResourceId").val().toString();
        node['text'] = $.trim($("#ResourceName").val().toString());
        node['type'] = "leaf";
        node['children'] = false;
        li_attr['fullname'] = $.trim($("#ParentResourceName").text()) + " → " + $.trim($("#ResourceName").val());
        node['li_attr'] = li_attr;

        return node;
    },
    FetchByKey: function (nodeId) {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/admin/resource/fetchByKey.html",
            timeout: 30 * 1000,
            data: JSON.stringify(nodeId),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            $("#ResourceId").val(data.resourceId);          // 系统资源ID
            $("#ParentId").val(data.parentId);              // 系统资源ID
            $("#OrderNo").val(data.orderNo);                // 系统资源编码
            $("#ResourceName").val(data.resourceName);      // 系统资源
            $("#LinkUrl").val(data.linkUrl);                // 系统资源路径
            $("#Description").val(data.description);        // 备注
            // 得到操作动作列表
            let actionList = data.actionList;
            if (actionList.length > 0) {
                for (let i = 0; i < actionList.length; i++) {
                    let _elmid = "c-" + actionList[i].actionId;
                    $("#" + _elmid).prop("checked", "true");
                    $("#" + _elmid).next().addClass('selected');
                }
            }
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function ( ) {
        });
    },
    //保存数据
    DoSave: function () {
        // 设置为无效状态
        if (parseInt(status) === -1) {
            ShowErrorMessagePanel("对不起，不能修改系统预设信息。");
            return false;
        }
        let ref = $.jstree.reference('treeContent');
        let sel = ref.get_selected()[0];
        if (sel === undefined) {
            ShowErrorMessagePanel("请选择系统资源。");
            return false;
        }

        if (!$("#form_data").valid())
            return false;

        if ($("input[type='checkbox'][name='action']:checked").length === 0) {
            ShowErrorMessagePanel("至少选择一个所属功能操作。");
            return false;
        }

        //step 2、执行处理
        $.ajax({
            type: "POST",
            url: parent.basePath + "/admin/resource/save.html",
            timeout: 30 * 1000,
            data: thisPage.GetEntityData(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                showLoadmask();
            }
        }).done((data) => {
            if (parseInt(data) > 0) {
                let ref = $.jstree.reference('treeContent');
                let sel = ref.get_selected()[0];
                let _obj = $("#" + sel);
                switch (parseInt(status)) {
                    case 0: //  编辑
                        // 修改路径名
                        let _fullname = $.trim($("#ParentResourceName").text()) + " → " + $.trim($("#ResourceName").val());
                        _obj.attr("fullname", _fullname);
                        ref.rename_node(_obj, $.trim($("#ResourceName").val())); // 修改节点文字
                        break;
                    case 1: // 新增
                        $("#ResourceId").val(data);   // 设置刚刚插入的资源ID
                        // 增加树形节点
                        ref.create_node(_obj, thisPage.NewNode());
                        ref.load_node(_obj);
                        ref.open_node(_obj);
                        // 取消当前选择点
                        ref.deselect_node(_obj);
                        // 选择该结点
                        let _newNode = $("#" + data);
                        ref.select_node(_newNode);
                        status = 0; // 设置为编辑状态
                        break;
                }
                ShowSuccessMessagePanel("保存成功。");
            }
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function ( ) {
            hideLoadmask();
        });
    },
    // 新增信息
    DoInsert: function () {
        let ref = $.jstree.reference('treeContent');
        let sel = ref.get_selected()[0];
        if (sel === undefined) {
            ShowErrorMessagePanel("请选择一个所属系统资源。");
            return;
        }

        status = 1; // 设置为新增状态

        // 清空表单内容，准备下一个记录
        thisPage.ClearForm();
        $("#OperateMode").html("<i class='fa-all fa-fw fa-pencil-square-o'></i>【操作状态】：增加系统资源");
        let _selectedNodeId = sel === "j1_1" ? 0 : sel;
        let _select_node = $("#" + sel);
        $('#ParentResourceName').val(_select_node.attr("fullname"));
        $('#ParentId').val(_selectedNodeId);
        $('#id').val("0");

        // 设置焦点
        $("#OrderNo").focus();
    },
    // 删除
    DoDelete: function () {
        let ref = $.jstree.reference('treeContent');
        let sel = ref.get_selected()[0];
        if (sel === undefined) {
            ShowErrorMessagePanel("请选择系统资源。");
            return false;
        }
        if (sel === "j1_1") {
            ShowErrorMessagePanel("不能删除系统预设信息。");
            return false;
        }
        showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要删除当前记录吗？', () => {
            let instance = {};
            instance['resourceId'] = $("#ResourceId").val();
            $.ajax({
                type: "POST",
                url: parent.basePath + "/admin/resource/delete.html",
                timeout: 30 * 1000,
                data: JSON.stringify(instance),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: function () {
                }
            }).done(data => {
                if (data > 0) {
                    // 删除树形节点
                    let sel = $.jstree.reference('treeContent').get_selected()[0];
                    $.jstree.reference('treeContent').delete_node(sel);

                    // 删除成功后，清空右侧表单内容
                    thisPage.ClearForm();
                    $("#OperateMode").html("");
                    $('#ParentResourceName').text("");
                }
            }).fail(data => {
                ajaxError(data, 1);
            }).always(( ) => {
            });
        });
    },
    ClearForm: function () {
        // 清空表单内容，准备下一个记录
        $(':input', '#form_data').not(':button, :submit, :reset, :hidden')
                .val('').removeAttr('checked').removeAttr('selected');
        $("input[type='checkbox'][name='action']:checked").each(function () {
            $(this).prop("checked", false);
        });
        $('#form_data')[0].reset();
        $(".error").removeClass("error");
        $(".tooltip").remove();
        $("i[generated='true']").remove();         // 删除错误图标

        $("#ActionWrapper").find('label').removeClass('selected');
        $("#ResourceId").val(0);
        $("#OrderNo").focus();
    }
};

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    // 用于判断表单是否有更改
    $("#form_data :input").change(function () {
        $("#form_data").data("changed", true);
    });
    $("#search_btn").hide();                  // 无需搜索，隐藏搜索按钮
    $("#form_data").data("changed", false);   // 初始化form数据提交状态

    thisPage.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    let h = $(window).height();
    let w = $(window).width();

    $("#treeArea").css({height: h - 110});
    $("#grid__wrapper").css({width: w - 8 - 275});
}

function checkField($self) {
    if ($self.is(':checked')) {
        $self.next().removeClass('selected').addClass('selected');
    } else
        $self.next().removeClass('selected');
}
//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _OrderNo: "required",
            _ResourceName: "required",
            _LinkUrl: "required"
        },
        messages: {
            _OrderNo: "请填写系统资源编码。",
            _ResourceName: "请填写系统资源。",
            _LinkUrl: "请填写系统访问路径。"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});
